<?php
/*
 * inc-addQuestion.php
 * Retral/CSCD494 Winter 2009
 * Eastern Washington University
 *
 * File Description:
 * 
 * This file is used to add questions into the database. Error checking is done
 * to make sure the user enters a title and uploads the required files. If the
 * required files are not specified the question is marked as incomplete but
 * still submitted.
 *
 * Other:
 *
 */


/* 
 * Set up $page_name
 * This name will be compared to PAGE_NAME in NAV_URLS table (stored in session) and verify permission for given user.
 */
$page_name = "Add Question";
$page_name = strtoupper($page_name);

require('KinID.php');

// Is user logged in, and has permissions?
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] !="" && $_SESSION['pagePermissions'][$page_name] == 1)
{

        // initializing variables
        $submitted = false;
        $questionLoaded = false;
        $pointsNotValid = false;
        $titleNotValid = false;
        $inputNotValid = false;
        $firstName = 'Non Existing User';
        $lastName  = '';
        $author = -1;
        
        echo '<h2>';
        echo "<span class='header-text'>Add Question</span><br/>";

            
        // connection to be used to connect to the database
        // ORA_CON_UN, ORA_CON_PW, ORA_CON_DB are global variables
        $conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
        
        
        $query = 'SELECT first_name, last_name ' .
                 ' FROM APE_USER' .
                 ' WHERE user_id = :userId ';
        $stmt = oci_parse($conn, $query);
        oci_bind_by_name($stmt, ':userId', $_SESSION['userID']);
        oci_execute($stmt, OCI_DEFAULT);

        if($result = oci_fetch_assoc($stmt))
        {
            do
            {     
                foreach ($result as $name => $column)
                {
                    if(strtoupper($name) == 'FIRST_NAME')
                        $firstName = $column;
                    else if(strtoupper($name) == 'LAST_NAME')
                        $lastName = $column;
                }
            }while($result = oci_fetch_assoc($stmt));
        } 
            
        $author = $_SESSION['userID'];
            
        $query = 'SELECT * 
                  FROM QUESTION_TYPE
                  ORDER BY type_code ASC ';
        $stmt = oci_parse($conn, $query);
        oci_execute($stmt);
        
        $pointsArray = array();
        $namesArray  = array();
        if($result = oci_fetch_assoc($stmt))
        {
            do
            {     
                foreach ($result as $name => $column)
                {
                   if(strtoupper($name) == 'TYPE_CODE')
                       $x = $column;                        
                   else if(strtoupper($name) == 'TYPE_DESCRIPTION')
                       $namesArray[$x] = strtoupper($column) ;
                   else if(strtoupper($name) == 'POINTS')
                   {
                       $pointsArray[$x] = $column;
                       $x++;
                   }

                }
            }while($result = oci_fetch_assoc($stmt));
        }

        if (isset($_POST['submit'])) 
        {
            $submitted = true;
            $pointsNotValid = ($submitted && strlen($_POST['points']) == 0) || preg_match("/\D/", $_POST['points']) != 0;
            $titleNotValid = $submitted && strlen(trim($_POST['question_title'])) == 0;
            $inputNotValid = $submitted && (empty($_FILES["pInput"]["name"]) || empty($_FILES["pOutput"]["name"])
                             //|| empty($_FILES["tInput"]["name"]) || empty($_FILES["tOutput"]["name"]) 
                             || empty($_FILES["criteria"]["name"]) || empty($_FILES["problem"]["name"]));        
            
            if(!$titleNotValid && !$pointsNotValid && $_POST['points'] <= $pointsArray[$_POST['questionType']])
            {
                $query = 
                    "INSERT INTO question_content (question_content_id, question_title, author_id, points) ".
                    "VALUES (question_content_s1.nextval, :title, :author, :points)";
                    
                $stmt = oci_parse($conn, $query);
                
                oci_bind_by_name($stmt, ':title', $_POST['question_title']);
                oci_bind_by_name($stmt, ':author', $author);    
                oci_bind_by_name($stmt, ':points', $_POST['points']);
                oci_bind_by_name($stmt, ':file_name', $_FILES['tInput']['name']);
                
                if(oci_execute($stmt, OCI_DEFAULT))
                {            
                    oci_commit($conn);
                    oci_free_statement($stmt);
                    
                    $query = 
                            " DECLARE " .
                            "     question_id_temp NUMBER := 0; " .
                            " BEGIN " .
                            "     SELECT question_s1.nextval INTO question_id_temp FROM DUAL; " .
                            "                                                                  " .
                            "     INSERT INTO question(question_id, q_version, question_type_code, question_content_id, date_modified, reviser_user_id) " .
                            "     VALUES (question_id_temp, 0, :type, question_content_s1.currval, SYSDATE, :author); " .
                            "                                                                                    " .
                            "     INSERT INTO change_request (question_id, q_version, request_code, comments) " .
                            "     VALUES (question_id_temp, 0, :code, :comments); " .
                            " END; ";
                    $stmt = oci_parse($conn, $query);
                   
                    
                    $requestCode = 2; // New question
                    //$comments = 'New Question';
                    $comments = ' ';
                    if($inputNotValid)
                    {
                        $requestCode = 6; // incomplete information
                        //$comments = 'Incomplete Information';
                    }    
                    oci_bind_by_name($stmt, ':type', $_POST['questionType']); 
                    oci_bind_by_name($stmt, ':code', $requestCode); 
                    oci_bind_by_name($stmt, ':comments', $comments); 
                    oci_bind_by_name($stmt, ':author', $author); 
                    
                    if(oci_execute($stmt, OCI_DEFAULT))
                    { 
                        oci_commit($conn);
                        oci_free_statement($stmt);
                        
                        $kin = 0;
                        $kinArray = array(provided_io(), provided_io(), test_io(), test_io(),  scoring(), instr());
                        $files = array("pInput", "pOutput", "tInput", "tOutput", "criteria", "problem");
                        
                        for($x = 0; $x < sizeof($files); $x++)
                        {
                            if(!empty($_FILES[$files[$x]]["name"]))
                            {
                                $kin = $kinArray[$x];
                                $query = 
                                        "INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file) ".
                                        "VALUES (source_file_s1.nextval, question_s1.currval, 0, :kin, :file_name, EMPTY_BLOB()) ". 
                                        "RETURNING source_file INTO :sourceFile ";
                                        
                                // Insert the BLOB from PHP's tempory upload area    
                                $lob_file = oci_new_descriptor($conn, OCI_D_LOB);  

                                $stmt = oci_parse($conn, $query);
                                oci_bind_by_name($stmt, ':file_name', $_FILES[$files[$x]]['name']);
                                oci_bind_by_name($stmt, ':kin', $kin);
                                oci_bind_by_name($stmt, ':sourceFile', $lob_file, -1, OCI_B_BLOB);
                                oci_execute($stmt, OCI_DEFAULT);
                                
                                if($lob_file->savefile($_FILES[$files[$x]]['tmp_name']))
                                {
                                    oci_commit($conn);
                                    oci_free_statement($stmt);
                                }
                                else
                                    echo "<script type=\"text/javascript\"> alert(\"ERROR!.\"); </script>";
                            }                            
                        }
                                               
                        echo "<span class='header-text'> <font color='#00FF00'> Question Successfully Uploaded! </font></span><br/>";                
                        
                        $numberOfSourceFiles = 1;
                        if($_POST['numberOfSourceFiles'] > 0)
                            $numberOfSourceFiles = $_POST['numberOfSourceFiles'];
                        for($x = 1; $x <= $numberOfSourceFiles; $x++)
                        {
                            $fileName = "source".$x;
                            $checked = false;
                            $kin = source_file();
                            if(!isset($_POST['check' . $x]))
                                $kin = class_file(); // Non Java File added as source
                            
                            if(!empty($_FILES[$fileName]["name"]))
                            {
                                $query = 
                                    "INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file) ".
                                    "VALUES (source_file_s1.nextval, question_s1.currval, 0, :kin, :file_name, EMPTY_BLOB()) ". 
                                    "RETURNING source_file INTO :sourceFile ";
                                    
                                    $lob_source_file = oci_new_descriptor($conn, OCI_D_LOB);   

                                    $stmt = oci_parse($conn, $query);
                                    oci_bind_by_name($stmt, ':file_name', $_FILES[$fileName]['name']);
                                    oci_bind_by_name($stmt, ':kin', $kin);
                                    oci_bind_by_name($stmt, ':sourceFile', $lob_source_file, -1, OCI_B_BLOB);
                                    oci_execute($stmt, OCI_DEFAULT);
                                    
                                    if($lob_source_file->savefile($_FILES[$fileName]['tmp_name']))
                                    {
                                        oci_commit($conn);
                                        oci_free_statement($stmt);
                                    }
                                    else
                                        echo "<script type=\"text/javascript\"> alert(\"ERROR!.\"); </script>"; 
                            }
                        }
                        $questionLoaded = true;
                        oci_commit($conn);
                           
                    }
                    else
                    {
                        echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! Contact the Administrator. </font></span><br/>";
                        $questionLoaded = true;                
                    }
                }
                else 
                {
                    echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! </font></span><br/>";
                    $questionLoaded = true;
                }        

                oci_free_statement($stmt);
                oci_close($conn); 
            }
            else
                echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! </font></span><br/>";
        }    
        echo '</h2>';
        

		?>

			<link rel="stylesheet" href="css/preview.css" type="text/css" media="screen">
			<script type="text/javascript" language="javascript" src="script/addQuestion.js"></script>
			<body onload="document.getElementById('<? if(isset($_POST['submit']) && $pointsNotValid && !$titleNotValid) echo 'points'; else echo 'question_title'; ?>').focus()">
			<form action="<?php echo $_SERVER['PHP_SELF'];  ?>?page=addQuestion&good=true" method="POST" enctype="multipart/form-data" >
			
				<p  class='required'>Author: <? echo $firstName; if($lastName != '') echo ', ' . $lastName; ?><br>
					Created: <?PHP echo date("m/d/Y"); ?>
				</p>
				
				<p><strong> <br>REQUIRED </strong></p>
				<p>
					<?
						if($titleNotValid)
						{    
							echo '<font color="#FF0000">Title: &nbsp</font>'; 
						} 
						else 
							echo 'Title: &nbsp';
					
					?>
					<input type='text' name='question_title' id='question_title' maxlength=40 class='required' value='<?=$_REQUEST['question_title']?>'> 
				
				
					<?
						if($titleNotValid)    
							echo '<br><font color="#FF0000">*Title can not be blank.</font>'; 
					?>
				</p>

				<p> Question Type:
					<select name="questionType" id="questionType" onChange="changePoints(this.form, this)">
					<?
						$max = 30;
						foreach($pointsArray as $index => $value)
						{
							echo '<option value =' . $index;
							if(isset($_POST['submit']) && $_POST['questionType'] == $index)
							{   echo " selected='yes'"; $max = $value; } 
							echo  '>' . strtoupper($namesArray[$index]);
							echo ' - ' . $value. ' points</option>';
						}   
					?>
					</select>
				</p>
				<p>
					<? 
						if($pointsNotValid)
						{    
							echo '<font color="#FF0000">Points Possible:</font>'; 
						} 
						else 
							echo 'Points Possible:';
					
						echo '<select name="points" id="points">';
					
						for($x = 5; $x <= $max; $x = $x + 5)
						{
							echo '<option value =' . $x;
							if(isset($_POST['submit']) && $_POST['points'] == $x)
								echo " selected='yes'"; 
							 echo  '>' . $x . '</option>';
						}   
					
						echo '</select>';
				   
						if($pointsNotValid)
							echo '<br><font color="#FF0000"> *Please make sure points are not blank and contain only digits without spaces. </font><br><br>';
						if($_POST['points'] > $pointsArray[$_POST['questionType']])
							echo '<br><font color="#FF0000"> *The question type you selected requires a maximum of ' . $pointsArray[$_POST['questionType']] . ' points. </font><br><br>';
					?>
				</p>
				<table>
					<tr>     Provided to Student: </tr>
					<tr><td> Input: </td> <td> <input type='file' name='pInput' id='pInput' class='required' value=''> </td></tr>
				<tr><td> Ouptut: </td> <td> <input type='file' name='pOutput' id='pOutput' class='required' value=''> </td></tr>
				</table> <br />
				<table>
					<tr>     Grading: </tr>
					<tr><td> Input:     </td> <td> <input type='file' name='tInput' class='required' value=''>   </td></tr>
					<tr><td> Ouptut:    </td> <td> <input type='file' name='tOutput' class='required' value=''>  </td></tr>
					<tr><td> Criteria:  </td> <td> <input type='file' name='criteria' class='required' value=''> </td></tr>
				</table>
				<p>Problem Instructions:
					<br><input type='file' name='problem' class='required' value=''>
				</p>
				<p><strong> <br>OPTIONAL </strong></p>
				
					<table>
					<tr><td> Question Source/Class Files: </td></tr>
					<tr>
						<td><input type='file' name='source1' class='required' value=''> </td>
						<td><input type='checkbox' name='check1' class='required' value='' <? if(!isset($_POST['submit']) || isset($_POST['check1'])) echo "checked"; ?> > Provide As Source <br> </td>
					</tr>
					<?
						for($x = 2; $x <= $_POST['numberOfSourceFiles']; $x++)
						{   
							echo "<tr><td><input type='file' name='source" . $x . "' class='required' value=''> </td>";
							if(!isset($_POST['submit']))
								echo "<td><input type='checkbox' name='check" . $x . "' class='required' value='' checked> Provide As Source<br> </td></tr>";
							else
							{
								echo "<td><input type='checkbox' name='check" . $x . "' class='required' value='' ";
								if(isset($_POST['check' . $x])) 
									echo 'checked'; 
								echo " > Provide As Source <br> </td></tr>";
							}
						}   
						
						if($_POST['numberOfSourceFiles'] >= 1)
							echo "<input type='hidden' name='numberOfSourceFiles'  value='" . $_POST['numberOfSourceFiles'] . "'>";
					?>
					</table>
					
			   
				<p><input class='button' type='submit' value='Upload' name='submit' id='submit'></p>
		  

			</form>
			</body>
<?php
}
else
{
	echo "Invalid credentials";
	echo "<META http-equiv=\"refresh\" content=\"0;URL=index.php?page=login&ld=0\">";
}	
?>
